import 'package:flutter/material.dart';
import 'package:flutter_default_project/models.dart';
import 'package:flutter_default_project/screens/detail_screen.dart';
import 'package:flutter_default_project/state_container.dart';

class TodoItem extends StatelessWidget {
  final Todo todo;
  final ValueChanged<bool?> onChanged;
  const TodoItem({super.key, required this.todo, required this.onChanged});

  void _showUndoSnackbar(BuildContext context, Todo todo) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text('"${todo.task}" task completed'),
        action: SnackBarAction(
          label: 'Undo',
          onPressed: () {
            StateContainer.of(context).addTodo(todo);
          },
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Navigator.of(context)
            .push(
              MaterialPageRoute(
                builder: (_) {
                  return DetailScreen(todo: todo);
                },
              ),
            )
            .then((todo) {
              if (todo is Todo) {
                _showUndoSnackbar(context, todo);
              }
            });
      },
      child: Dismissible(
        key: ValueKey(todo.id),
        onDismissed: (direction) {
          StateContainer.of(context).removeTodo(todo);
        },
        child: ListTile(
          leading: Checkbox(value: todo.complete, onChanged: onChanged),
          title: Text(todo.task),
          subtitle: Text(todo.note),
        ),
      ),
    );
  }
}
